<template>
  <div class="agent-management-container">
    <div class="agent-header">
      <h2>智能体管理</h2>
      <div class="agent-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索智能体"
          prefix-icon="Search"
          clearable
          @input="filterAgents"
        />
        <el-button type="primary" @click="showAddAgentDialog">
          <el-icon><Plus /></el-icon>添加智能体
        </el-button>
      </div>
    </div>

    <div class="agent-content">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <div 
        v-else-if="filteredAgents.length === 0" 
        class="empty-agent"
      >
        <el-empty description="暂无智能体" />
      </div>
      
      <div v-else class="agent-grid">
        <div 
          v-for="agent in filteredAgents" 
          :key="agent.id" 
          class="agent-card"
          @dblclick="editAgent(agent)"
        >
          <div class="agent-card-header">
            <div class="agent-icon">
              <el-icon><Avatar /></el-icon>
            </div>
            <el-dropdown trigger="click" @command="handleCommand($event, agent)" @click.stop>
              <span class="more-actions">
                <el-icon><MoreFilled /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit">编辑</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div class="agent-card-content">
            <h3 class="agent-name">{{ agent.name }}</h3>
            <p class="agent-description">{{ agent.description || '暂无描述' }}</p>
          </div>
          <div class="agent-card-footer">
            <span class="agent-method">{{ agent.method }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑智能体弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑智能体' : '添加智能体'"
      width="650px"
    >
      <el-form 
        :model="currentAgent" 
        label-width="100px"
        :rules="agentRules"
        ref="agentFormRef"
      >
        <el-form-item label="ID" prop="id">
          <el-input v-model="currentAgent.id" placeholder="请输入智能体ID" />
        </el-form-item>
        
        <el-form-item label="名称" prop="name">
          <el-input v-model="currentAgent.name" placeholder="请输入智能体名称" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="currentAgent.description" 
            type="textarea" 
            rows="3" 
            placeholder="请输入智能体描述"
          />
        </el-form-item>
        
        <el-form-item label="方法文件" prop="method">
          <div class="method-input-container">
            <el-input 
              v-model="currentAgent.method" 
              placeholder="请输入方法文件名称，例如: MyAgent.py" 
              :disabled="isUploading"
            />
            <span class="or-separator">或</span>
            <el-upload
              class="method-upload"
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :before-upload="beforeUpload"
              :limit="1"
              accept=".py"
              :file-list="fileList"
            >
              <el-button type="primary" :loading="isUploading">选择文件</el-button>
            </el-upload>
          </div>
          <div v-if="fileList.length > 0" class="selected-file-info">
            <span>已选择: {{ fileList[0].name }}</span>
            <el-button 
              type="success" 
              size="small" 
              @click="uploadFile" 
              :loading="isUploading"
              :disabled="!fileList.length"
            >
              上传到服务器
            </el-button>
          </div>
        </el-form-item>
        
        <el-divider content-position="center">参数配置</el-divider>
        
        <div class="parameters-container">
          <div v-for="(value, key, index) in currentAgent.parameters" :key="index" class="parameter-item">
            <el-input v-model="parameterKeys[index]" placeholder="参数名称" />
            <el-input v-model="currentAgent.parameters[key]" placeholder="参数描述" />
            <el-button type="danger" circle @click="removeParameter(key)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
          
          <div class="add-parameter">
            <el-button type="primary" plain @click="addParameter">
              <el-icon><Plus /></el-icon>添加参数
            </el-button>
          </div>
        </div>
        
        <el-form-item label="执行结果消息" prop="required">
          <el-input 
            v-model="currentAgent.required" 
            placeholder="请输入执行结果消息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAgent" :loading="saving">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认删除对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="300px"
    >
      <p>确定要删除智能体"{{ currentAgent.name }}"吗？</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete" :loading="deleting">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, reactive } from 'vue';
import { Plus, Search, Avatar, MoreFilled, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import type { UploadFile, UploadUserFile } from 'element-plus';

interface AgentParameter {
  [key: string]: string;
}

interface Agent {
  id: string;
  name: string;
  description: string;
  method: string;
  parameters: AgentParameter;
  required: string;
}

// 表单校验规则
const agentRules = reactive<FormRules>({
  id: [
    { required: true, message: '请输入智能体ID', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入智能体名称', trigger: 'blur' },
    { min: 2, message: '名称长度不能小于2个字符', trigger: 'blur' }
  ],
  method: [
    { required: true, message: '请输入方法文件名称或上传文件', trigger: 'blur' },
    { pattern: /\.py$/, message: '方法文件必须是.py文件', trigger: 'blur' }
  ]
});

// 状态变量
const searchQuery = ref('');
const dialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const isEditing = ref(false);
const loading = ref(true);
const saving = ref(false);
const deleting = ref(false);
const isUploading = ref(false);
const fileList = ref<UploadUserFile[]>([]);
const parameterKeys = ref<string[]>([]);
const agents = ref<Agent[]>([]);
const agentFormRef = ref<FormInstance>();

// 当前操作的智能体对象
const currentAgent = ref<Agent>({
  id: '',
  name: '',
  description: '',
  method: '',
  parameters: {},
  required: ''
});

// 根据搜索关键词过滤智能体
const filteredAgents = computed(() => {
  if (!searchQuery.value) return agents.value;
  const query = searchQuery.value.toLowerCase();
  return agents.value.filter(agent => 
    agent.name.toLowerCase().includes(query) || 
    agent.description.toLowerCase().includes(query)
  );
});

// 过滤智能体方法
const filterAgents = () => {
  // 搜索功能已通过计算属性实现
};

// 显示添加智能体对话框
const showAddAgentDialog = () => {
  isEditing.value = false;
  currentAgent.value = {
    id: '',
    name: '',
    description: '',
    method: '',
    parameters: {},
    required: ''
  };
  parameterKeys.value = [];
  fileList.value = [];
  dialogVisible.value = true;
};

// 获取下一个可用ID
const getNextId = (): string => {
  if (agents.value.length === 0) return '1';
  return String(Math.max(...agents.value.map(agent => parseInt(agent.id))) + 1);
};

// 编辑智能体
const editAgent = (agent: Agent) => {
  isEditing.value = true;
  // 深拷贝以防止直接修改引用
  currentAgent.value = JSON.parse(JSON.stringify(agent));
  
  // 重置参数键数组
  parameterKeys.value = Object.keys(agent.parameters || {});
  
  fileList.value = [];
  dialogVisible.value = true;
};

// 处理下拉菜单命令
const handleCommand = (command: string, agent: Agent) => {
  if (command === 'edit') {
    editAgent(agent);
  } else if (command === 'delete') {
    currentAgent.value = agent;
    deleteDialogVisible.value = true;
  }
};

// 添加参数
const addParameter = () => {
  const newKey = `param${Object.keys(currentAgent.value.parameters).length + 1}`;
  parameterKeys.value.push(newKey);
  currentAgent.value.parameters[newKey] = '';
};

// 移除参数
const removeParameter = (key: string) => {
  const index = parameterKeys.value.indexOf(key);
  if (index !== -1) {
    parameterKeys.value.splice(index, 1);
  }
  const newParams: AgentParameter = {};
  for (let i = 0; i < parameterKeys.value.length; i++) {
    const paramKey = parameterKeys.value[i];
    const values = Object.values(currentAgent.value.parameters);
    if (i < values.length) {
      newParams[paramKey] = String(values[i]);
    }
  }
  currentAgent.value.parameters = newParams;
};

// 处理文件变更
const handleFileChange = (uploadFile: UploadFile) => {
  fileList.value = [uploadFile];
  if (uploadFile.name) {
    currentAgent.value.method = uploadFile.name;
  }
};

// 上传前校验
const beforeUpload = (file: File) => {
  const isPython = file.name.endsWith('.py');
  if (!isPython) {
    ElMessage.error('只能上传Python脚本文件!');
    return false;
  }
  return true;
};

// 上传文件到服务器
const uploadFile = async () => {
  if (!fileList.value.length) return;
  
  const file = fileList.value[0].raw;
  if (!file) {
    ElMessage.warning('无法读取文件');
    return;
  }
  
  isUploading.value = true;
  
  try {
    const formData = new FormData();
    formData.append('file', file);
    
    // 上传文件到服务器
    const response = await fetch('/api/agents/upload-agent-file', {
      method: 'POST',
      body: formData
    });
    
    if (response.ok) {
      const data = await response.json();
      ElMessage.success('文件上传成功');
      currentAgent.value.method = file.name;
    } else {
      const errorData = await response.json();
      ElMessage.error(`上传失败: ${errorData.detail || '未知错误'}`);
    }
  } catch (error) {
    console.error('上传文件错误:', error);
    ElMessage.error('上传文件时发生错误');
  } finally {
    isUploading.value = false;
  }
};

// 保存智能体
const saveAgent = async () => {
  if (!agentFormRef.value) return;
  
  await agentFormRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true;
      
      try {
        // 重建参数对象，确保使用最新的参数键
        const updatedParameters: AgentParameter = {};
        for (let i = 0; i < parameterKeys.value.length; i++) {
          const key = parameterKeys.value[i];
          const value = Object.values(currentAgent.value.parameters)[i];
          updatedParameters[key] = value;
        }
        currentAgent.value.parameters = updatedParameters;
        
        // 发送保存请求
        const url = isEditing.value ? `/api/agents/list/${currentAgent.value.id}` : '/api/agents/list';
        const method = isEditing.value ? 'PUT' : 'POST';
        
        const response = await fetch(url, {
          method,
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(currentAgent.value),
        });
        
        if (response.ok) {
          if (isEditing.value) {
            // 更新列表中的智能体
            const index = agents.value.findIndex(a => a.id === currentAgent.value.id);
            if (index !== -1) {
              agents.value[index] = { ...currentAgent.value };
            }
            ElMessage.success('智能体已更新');
          } else {
            // 添加新智能体到列表
            agents.value.push({ ...currentAgent.value });
            ElMessage.success('智能体已添加');
          }
          dialogVisible.value = false;
        } else {
          const errorData = await response.json();
          ElMessage.error(`保存失败: ${errorData.detail || '未知错误'}`);
        }
      } catch (error) {
        console.error('保存智能体错误:', error);
        ElMessage.error('保存智能体时发生错误');
      } finally {
        saving.value = false;
      }
    } else {
      ElMessage.warning('请完成必填项');
    }
  });
};

// 确认删除
const confirmDelete = async () => {
  deleting.value = true;
  
  try {
    // 发送删除请求
    const response = await fetch(`/api/agents/list/${currentAgent.value.id}/True`, {
      method: 'DELETE',
    });
    
    if (response.ok) {
      // 从列表中移除
      agents.value = agents.value.filter(a => a.id !== currentAgent.value.id);
      deleteDialogVisible.value = false;
      ElMessage.success('智能体已删除');
    } else {
      const errorData = await response.json();
      ElMessage.error(`删除失败: ${errorData.detail || '未知错误'}`);
    }
  } catch (error) {
    console.error('删除智能体错误:', error);
    ElMessage.error('删除智能体时发生错误');
  } finally {
    deleting.value = false;
  }
};

// 获取智能体列表
const fetchAgents = async () => {
  loading.value = true;
  
  try {
    // 发送获取智能体列表请求
    const response = await fetch('api/agents/list');
    console.log("获取智能体列表请求：" +response);
    
    if (response.ok) {
      const data = await response.json();
      agents.value = data;
    } else {
      ElMessage.error('获取智能体列表失败');
    }
  } catch (error) {
    console.error('获取智能体列表错误:', error);
    ElMessage.error('获取智能体列表时发生错误');
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchAgents();
});

// 观察参数键的变化，同步更新参数对象
watch(parameterKeys, (newKeys, oldKeys) => {
  if (newKeys.length !== oldKeys.length) return;
  
  const newParams: AgentParameter = {};
  for (let i = 0; i < newKeys.length; i++) {
    const key = newKeys[i];
    const values = Object.values(currentAgent.value.parameters);
    if (i < values.length) {
      newParams[key] = String(values[i]);
    }
  }
  currentAgent.value.parameters = newParams;
}, { deep: true });
</script>

<style scoped>
.agent-management-container {
  height: 100%;
  padding: 1rem;
  display: flex;
  flex-direction: column;
}

.agent-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #e6e6e6;
}

.agent-header h2 {
  margin: 0;
  color: #334155;
  font-weight: 600;
  font-size: 1.5rem;
}

.agent-actions {
  display: flex;
  gap: 1rem;
}

.agent-content {
  flex: 1;
  overflow-y: auto;
  padding: 1rem 0;
}

.loading-container {
  padding: 2rem;
}

.agent-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1.2rem;
}

.agent-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 220px;
  cursor: pointer;
  border-top: 3px solid #8B5CF6;
}

.agent-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}

.agent-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background: linear-gradient(to right, #f9fafb, #f3f4f6);
}

.agent-icon {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #8B5CF6 0%, #6366F1 100%);
  color: white;
  border-radius: 8px;
}

.agent-icon .el-icon {
  font-size: 1.2rem;
}

.more-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 4px;
  cursor: pointer;
  color: #64748b;
}

.more-actions:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.agent-card-content {
  flex: 1;
  padding: 0.5rem 1rem 1rem;
  overflow: hidden;
}

.agent-name {
  margin: 0 0 0.5rem;
  font-size: 1.1rem;
  color: #1e293b;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.agent-description {
  color: #64748b;
  margin: 0;
  font-size: 0.9rem;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
}

.agent-card-footer {
  padding: 0.75rem 1rem;
  background-color: #f8fafc;
  font-size: 0.8rem;
  color: #94a3b8;
  border-top: 1px solid #f1f5f9;
}

.agent-method {
  font-family: monospace;
  font-size: 0.9rem;
}

.empty-agent {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
}

.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.method-input-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.or-separator {
  color: #94a3b8;
  font-size: 0.9rem;
}

.selected-file-info {
  margin-top: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  background-color: #f8fafc;
  border-radius: 4px;
  font-size: 0.9rem;
}

.parameters-container {
  margin-bottom: 1.5rem;
}

.parameter-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
}

.add-parameter {
  margin-top: 1rem;
  display: flex;
  justify-content: center;
}

/* 扩大对话框内容区域 */
:deep(.el-dialog__body) {
  padding: 20px 30px;
}
</style> 